package com.happy.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * Created by phshy on 2017/1/19.
 */
public class JSONUtils {
    private static final ObjectMapper mapper = new ObjectMapper();

    private JSONUtils() {
    }

    public static Map<String, Object> json2Map(String json) throws IOException {
        Map map = (Map) mapper.readValue(json, Map.class);
        return map;
    }

    public static String O2J(Object object) {
        try {
            return mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static <T> T J2O(String json, Class<T> clazz) {
        try {
            return mapper.readValue(json, clazz);
        } catch (IOException e) {
            e.printStackTrace();

            return null;
        }

    }

    public static List<?> json2List(String json, TypeReference<?> typeRef) throws IOException {
        List list = (List) mapper.readValue(json, typeRef);
        return list;
    }
}
